/**
 * @description: 校验方法
 * @file: rules.ts
 * @author: Evan
 * @date: 2025.05.08 15:42:44
 * @week: 周四
 * @version: V
 * */

import { reChinese, trims } from './format'
import { checkEmail, checkTel } from './validate'
import i18n from '@/locales'
const { t } = i18n.global

const $t = (text: string = '', params: AnyObject = {}) => {
  return t(`rule_tip.${text}`, params)
}

// 格式化编码
export const formatCode = (value: string, callback?: (e: any) => void) => {
  let text = value
  // 去除空格
  text = trims(text)
  // 去除汉字
  text = reChinese(text)

  if (typeof callback != 'function') return text
  return callback(text)
}

// 格式化编码 - 大写
export const formatUpperCode = (value: string, callback?: (e: any) => void) => {
  let text = value
  // 去除空格
  text = trims(text)
  // 去除汉字
  text = reChinese(text)
  text = text.toUpperCase()
  if (typeof callback != 'function') return text
  return callback(text)
}

// 格式化编码 - 小写
export const formatLowerCode = (value: string, callback?: (e: any) => void) => {
  if (typeof callback != 'function') return
  let text = value
  // 去除空格
  text = trims(text)
  // 去除汉字
  text = reChinese(text)
  text = text.toLowerCase()
  if (typeof callback != 'function') return text
  return callback(text)
}

// 校验邮箱
export const ruleEmail = (_rule: any, value: any, callback: (msg?: any) => void) => {
  if (value) {
    if (!checkEmail(value)) {
      let msg = $t('email')
      callback(new Error(msg))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

// 校验电话号码
export const ruleTel = (_rule: any, value: any, callback: (msg?: any) => void) => {
  if (value) {
    if (!checkTel(value)) {
      let msg = $t('tel')
      callback(new Error(msg))
    } else {
      callback()
    }
  } else {
    callback()
  }
}
